const validate = require('../middleware/validate');
const { body, param, validationResult } = require('express-validator');
const {Article} = require('../model')

exports.createArticle = validate([ // 1、配置验证规则
    body('article.title').notEmpty().withMessage('文章标题不能为空'),
    body('article.description').notEmpty().withMessage('文章摘要不能为空'),
    body('article.body').notEmpty().withMessage('文章内容不能为空')
])
exports.getArticle = validate([
    validate([
        validate.isValidObjectId(['params'], 'articleId')
    ])
])
exports.updateArticle = [
    validate([
        validate.isValidObjectId(['params'], 'articleId')
    ]),
    async (req, res, next)=>{
        const articleId = req.params.articleId
        const article = await Article.findById(articleId)
        req.article = article
        if(!article){
            return res.status(404).end('文章不存在')
        }
        next()
    },
    async (req, res, next)=>{
        if(req.user._id.toString() != req.article.author.toString()){
            return res.status(403).end('暂无权限')
        }
        next()
    }
]
exports.deleteArticle = exports.updateArticle